<template>
  <div>
    <div class="app-container">
      <el-row>
        <el-col :span="6"><el-input v-model="filterText" placeholder="输入父级品类模糊匹配" /></el-col>
      </el-row>

      <tree-table
        ref="TreeTable"
        :data="tableData.filter(data => !filterText || data.categoryName.toLowerCase().includes(filterText.toLowerCase()))"
        :default-expand-all="false"
        :columns="columns"
        border
        default-children="children"
        highlight-current-row
        @selection-change="selectChange"
      >
        <template slot="selection">
          <el-table-column type="selection" align="center" width="55" />
        </template>

        <template slot="categoryLogoPath" slot-scope="{scope}">
          <img :src="scope.row.categoryLogoPath" style="height: 50px;">
        </template>

        <template slot="operation" slot-scope="{scope}">
          <el-button size="mini" type="primary" @click="addMenuItem(scope.row,'children')">添加子品类</el-button>
          <el-button size="mini" type="success" @click="editItem(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteItem(scope.row)">删除</el-button>
        </template>
      </tree-table>
    </div>

    <el-dialog :visible.sync="dialogFormVisible" title="编辑" width="550px">
      <el-form :model="tempItem" label-width="100px">
        <el-form-item label="品类名称" prop="categoryName">
          <el-input v-model.trim="tempItem.categoryName" placeholder="品类" />
        </el-form-item>
        <el-form-item label="品类logo" prop="logo">
          <el-upload
            ref="uploadImage"
            :class="{disabled:uploadDisabled}"
            :limit="1"
            :file-list="imageFileList"
            :on-preview="handlePictureCardPreview"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :auto-upload="false"
            action="string"
            list-type="picture-card">
            <i class="el-icon-plus"/>
          </el-upload>
          <el-dialog :visible.sync="previewVisible">
            <img :src="dialogImageUrl" width="100%" alt>
          </el-dialog>
        </el-form-item>.
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveItem">保存</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import TreeTable from '@/components/TreeTable'
import { listCategory, saveCategory, deleteCategory } from '@/api/category'
export default {
  components: { TreeTable },
  data() {
    return {
      filterText: '',

      imageFileList: [],
      previewVisible: false,
      dialogImageUrl: [],
      previewUrl: '',

      tableData: [],
      tempItem: {},
      imageData: {},

      dialogFormVisible: false,
      columns: [
        {
          label: '品类',
          key: 'categoryName',
          expand: true,
          width: 300
        },
        {
          label: 'logo',
          key: 'categoryLogoPath',
          width: 200
        },
        {
          label: '操作',
          key: 'operation',
          width: 300
        }
      ]
    }
  },
  computed: {
    uploadDisabled: function() {
      return this.imageFileList.length > 0
    }
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      // this.tableData = data
      //
      var data = {}
      listCategory(data).then(
        response => {
          if (response.data.status === 'success') {
            // 保存之前展开的状态
            var resultData = response.data.data
            var addoffse = 0
            for (var i = 0, j = i - addoffse; i < resultData.length; i++) {
              for (;j < this.tableData.length; j++) {
                if (resultData[i].categoryId === this.tableData[j].categoryId) {
                  resultData[i]._expand = this.tableData[j]._expand
                  break
                }
                // 没有找到 就是新增的
                addoffse++
              }
            }
            this.tableData = resultData
          } else {
            this.$message({
              message: '品类加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },
    editItem(row) {
      this.tempItem = Object.assign({}, row)
      this.imageFileList = []
      if (row.categoryLogoPath) {
        this.imageFileList.push({ name: 'logo', url: row.categoryLogoPath })
      }
      this.dialogFormVisible = true
    },
    async saveItem() {
      // 请求添加 or 更新
      var addData = new FormData()
      addData.append('categoryId', this.tempItem.categoryId ? this.tempItem.categoryId : '')
      addData.append('categoryName', this.tempItem.categoryName ? this.tempItem.categoryName : '')
      addData.append('parentCategoryId', this.tempItem.parentCategoryId ? this.tempItem.parentCategoryId : '')
      addData.append('categoryLogo', this.imageFileList[0] ? this.imageFileList[0].raw : '')

      saveCategory(addData).then(
        response => {
          if (response.data.status === 'success') {
            this.getData()
            this.dialogFormVisible = false
            // await this.$refs.TreeTable.updateTreeNode(this.tempItem)
            // this.dialogFormVisible = false
          } else {
            this.$message({
              message: '品类保存失败' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },
    addMenuItem(row, type) {
      row._expand = true
      if (type === 'children') {
        this.$refs.TreeTable.addChild(row, { categoryName: '请编辑', parentCategoryId: row.categoryId, categoryLogoPath: '' })
      }
      if (type === 'brother') {
        this.$refs.TreeTable.addBrother(row, { categoryName: 'brother', categoryLogoPath: '' })
      }
    },
    deleteItem(row) {
      if (this.deleteCategory(row)) { // 删除成功更新视图
        // var parent = row._parent
        this.$refs.TreeTable.delete(row)
      }
    },
    openCurrentNode(row) {
      if (row) {
        row._expand = true
        if (row._parent) {
          this.openCurrentNode(row._parent)
        }
      }
    },
    selectChange(val) {
      console.log(val)
    },
    handleChange(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isLt2M) {
        this.$refs.uploadImage.clearFiles()
        this.$message.error('上传头像图片大小不能超过 1M')
        return false
      }
      this.imageData = file.raw
      this.imageFileList = fileList
    },
    handleRemove(file, fileList) {
      this.imageData = null
      this.imageFileList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = URL.createObjectURL(file.raw)
      this.previewVisible = true
    },

    deleteCategory(row) {
      this.$confirm('确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCategory(row.categoryId).then(
          response => {
            if (response.data.status === 'success') {
              this.getData()
            } else {
              this.$message({
                message: '操作失败' + response.data.messge,
                type: 'warning'
              })
            }
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    }

  }
}
</script>

<style>
.disabled .el-upload--picture-card {
    display: none;
}

.el-row {
    margin-bottom: 20px;
}

.el-table td {
    padding: 0 0 0 0;
}
</style>
